<template>
  <div class="flex">
    <side-bar :has-agent="hasAgent" ref="sideRef" @on-node-click="onNodeClick" />
    <page-box>
      <template #search>
        <search-form :fieldList="fieldList" :form="query" @onSearchFun="onPageChange(1)"></search-form>
      </template>
      <template #btn>
        <el-button @click="onPageChange">查询</el-button>
        <el-button type="primary" @click="onJump">新建</el-button>
      </template>
      <template #table>
        <resize-table
          ref="tableRef"
          :showPagination="true"
          @onPageChange="onPageChange"
          @onPageSizeChange="onPageSizeChange"
          :data="list"
          :pagingData="page"
          :headers="headers"
          selection
          :batchs="cmpBatches"
          @onBatchClick="onBatchClick"
        >
          <template #status="{ scope }">
            <el-switch
              v-if="typeof scope.row.status === 'number'"
              @change="(val: any) => onChangeStatus(val, scope.row)"
              :active-value="1"
              :inactive-value="0"
              inline-prompt
              v-model="scope.row.status"
            ></el-switch>
          </template>
          <template #operation="{ scope }">
            <el-button type="primary" link @click="onJump(scope.row)">编辑</el-button>
            <el-button v-if="isGroup" type="primary" link @click="onOpenDel(scope.row)">移除</el-button>
          </template>
        </resize-table>
      </template>
    </page-box>
    <el-dialog v-model="roleVisible" title="批量修改角色">
      <search-form :fieldList="editRole.fieldList" :form="editRole.form"></search-form>
    </el-dialog>
    <div class="dialog">
      <el-dialog v-model="groupVisible" title="批量修改分组">
        <search-form
          ref="groupRef"
          :rules="groupRules"
          :fieldList="editGroup.fieldList"
          :form="editGroup.form"
        ></search-form>
        <div class="btn-box">
          <el-button class="ml10" @click="onHide">取消</el-button>
          <el-button class="ml6" @click="onConfirmGroup" type="primary">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts">
import SideBar from './side-bar.vue'
import { Search } from '@element-plus/icons-vue'
import { reactive, toRefs, defineComponent, toRaw, onMounted, ref, computed } from 'vue'
import resizeTable from '@/common/components/resize-table/index.vue'
import usePage from '@/common/utils/hooks/use-page'
import { ElMessage, ElMessageBox } from 'element-plus'
import { batchChangeStatus, agentUpdate, getServiceGroup, serviceGroupBatchMove, batchDel } from '@/app/base/apis/staff'
import * as actions from '../constance'
import PageBox from '@/common/components/page-box.vue'
import searchForm from '@/common/components/base-form/form.vue'
import { useRouter } from 'vue-router'
import localforage from 'localforage'
import { IS_GROUP, MEMBER_STORE_PRE, UN_GROUP, URL_MAP } from './constance'
import { flatten } from '@/common/utils/common'
import mcGetCache from '@/common/utils/mc-get-cache'

interface BaseFormProps {
  fieldList: Record<string, unknown>[]
  form: Record<string, unknown>
}
interface State {
  node: Record<string, unknown>
  url: string
  roleVisible: boolean
  roleOptions: any[]
  editRole: BaseFormProps
  groupVisible: boolean
  groupOptions: any[]
  editGroup: BaseFormProps
  input: HTMLInputElement | null
  query: Record<string, unknown>
  headers: Record<string, unknown>[]
  members: any[]
  showPage: boolean
  fileList: any[]
  batchs: Record<string, unknown>[]
  fieldList: any[]
}
export default defineComponent({
  name: 'enterprise-staff',
  components: { resizeTable, PageBox, SideBar, searchForm },
  setup() {
    const state: State = reactive({
      fieldList: [
        {
          name: '员工搜索',
          field: 'quickSearch',
          type: 'text',
          placeholder: '请输入工号/姓名/手机号码'
        },
        {
          name: '状态',
          field: 'status',
          type: 'dropdown',
          choices: [
            { value: '', label: '全部' },
            { value: 0, label: '停用' },
            { value: 1, label: '启用' }
          ]
        }
      ],
      batchs: [
        { name: '批量停用', action: actions.BATCH_DISABLE },
        { name: '批量启用', action: actions.BATCH_ENABLE },
        { name: '批量修改分组', action: actions.BATCH_EDIT_GROUP },
        { name: '批量移除', action: actions.BATCH_REMOVE }
      ],
      node: {},
      url: '/platform/action/agent/list',
      members: [{}],
      fileList: [],
      roleVisible: false,
      roleOptions: [
        { value: '', label: '全部' },
        { value: 0, label: '员工' },
        { value: 1, label: '管理员' }
      ],
      editRole: {
        fieldList: [
          {
            field: 'editRole',
            type: 'dropdown',
            choices: [
              { value: 0, label: '员工' },
              { value: 1, label: '管理员' }
            ]
          }
        ],
        form: { editRole: [] }
      },
      groupVisible: false,
      groupOptions: [
        { value: '', label: '全部' },
        { value: 0, label: '员工' },
        { value: 1, label: '管理员' }
      ],
      editGroup: {
        fieldList: [
          {
            name: '服务组',
            field: 'editGroup',
            type: 'dropdown',
            choices: [
              { value: 0, label: '员工' },
              { value: 1, label: '管理员' }
            ]
          }
        ],
        form: { editGroup: [] }
      },
      input: null,
      query: {
        quickSearch: undefined,
        status: '',
        groups: []
      },
      headers: [
        {
          label: '工号',
          fixed: true,
          show: true,
          prop: 'agentNumber',
          sortable: true
        },
        {
          label: '姓名',
          show: true,
          prop: 'agentName'
        },
        {
          label: '状态',
          show: true,
          prop: 'status',
          custom: true
        },
        {
          label: '操作',
          show: true,
          prop: 'operation',
          disenable: true,
          width: 150,
          custom: true
        }
      ],
      showPage: false
    })
    const groupRef: any = ref(null)
    const tableRef: any = ref(null)
    const sideRef: any = ref(null)
    const batchData: any = []
    const groupRules = { editGroup: [{ required: true, message: '必选项', trigger: 'change' }] }
    const getUrl = () => state.url
    const { list, page, onPageChange, onPageSizeChange } = usePage({
      getUrl,
      reqParams: state.query,
      pageReqKeys: {
        'page-size': 'pageSize',
        'current-page': 'page',
        total: 'count',
        'page-sizes': 'page-sizes'
      },
      pageResKeys: {
        list: 'data.list',
        total: 'data.count'
      }
    })

    const hasAgent: any = computed(() => list.value.length)

    const batchDisable = async (list: any) => {
      const agentIds = getBatchIds(list)
      await batchChangeStatus({
        agentIds: getBatchIds(list),
        query: {
          status: 0
        },
        status: 0
      })
      console.log(agentIds)
      agentIds.forEach((i: string) => {
        mcGetCache.$updateCacheBySingleKey('userCache', { _id: i, key: 'status', value: 0 }, '_id', 'hasObj')
      })
    }

    const onConfirmGroup = async () => {
      const pass = await groupRef.value?.checkForm()
      if (!pass) {
        return
      }
      const isSelectAll = batchData.value === true
      await serviceGroupBatchMove({
        agentIds: isSelectAll ? null : batchData.value,
        newGroupNumber: state.editGroup.form.editGroup,
        groupNumber: (state.query as any).groups[0],
        ...(isSelectAll
          ? {
              checkAll: {
                ...state.query,
                type: cmpType.value
              }
            }
          : {})
      })
      state.editGroup.form.editGroup = []
      state.groupVisible = false
      onPageChange()
      sideRef.value.getData()
      ElMessage.success('操作成功')
    }

    const batchEnable = async (list: any) => {
      const agentIds = getBatchIds(list)
      await batchChangeStatus({
        agentIds: getBatchIds(list),
        query: {
          status: 1
        },
        status: 1
      })
      agentIds.forEach((i: string) => {
        mcGetCache.$updateCacheBySingleKey('userCache', { _id: i, key: 'status', value: 1 }, '_id', 'hasObj')
      })
    }

    const batchOpenRole = (list: any) => {
      state.roleOptions = list
      onVisible(true)
    }

    const batchEdit = (isRole?: boolean) => {
      console.log(state.roleOptions, isRole)
    }

    const batchOpenGroup = (list: any) => {
      batchData.value = list
      state.groupVisible = true
      getFlattenGroup()
    }

    const batchEditGroup = (list: any) => {
      state.roleOptions = list
      onVisible()
    }

    // const getBatchIds = (data: any) => (data === true ? (list as any).value.map((i: any) => i._id) : data)
    const getBatchIds = (data: any) => (data === true ? [] : data)

    const batchRemove = async (list: any) => {
      await onOpenDel(getBatchIds(list), list)
    }

    const actionMap: any = new Map([
      [actions.BATCH_DISABLE, batchDisable],
      [actions.BATCH_ENABLE, batchEnable],
      [actions.BATCH_EDIT_ROLE, batchOpenRole],
      [actions.BATCH_EDIT_GROUP, batchOpenGroup],
      [actions.BATCH_REMOVE, batchRemove]
    ])

    const onBatchClick = async (action: actions.Action, list: any) => {
      await actionMap.get(action)(list)
      tableRef.value.cancelSelectFun()
      onPageChange()
      if (action !== actions.BATCH_EDIT_ROLE && action !== actions.BATCH_EDIT_GROUP) {
        ElMessage.success('操作成功')
      }
    }
    const getFlattenGroup = async () => {
      const res = await getServiceGroup()
      state.editGroup.fieldList[0].choices = flatten(res.data).map((i: any) => ({
        ...i,
        value: i.groupNumber,
        label: i.name
      }))
    }

    const onVisible = (isRole?: boolean) => {
      state[isRole ? 'roleVisible' : 'groupVisible'] = true
      if (!isRole) {
        getFlattenGroup()
      }
    }

    const onHide = () => {
      state.groupVisible = false
    }
    const onChangeStatus = async (val: any, row: any) => {
      if (!row._id) {
        return
      }
      await agentUpdate({
        _id: row._id,
        status: val
      }).then(() => {
        ElMessage.success('操作成功')
        mcGetCache.$updateCacheBySingleKey('userCache', { _id: row._id, key: 'status', value: val }, '_id', 'hasObj')
      })
      onPageChange()
    }

    const onDel = async (row: any, data?: any) => {
      const { _id } = row
      const { groupNumber } = state.node
      const agentIds = Array.isArray(row) ? row : [_id]
      const isSelectAll = data === true
      console.log(isSelectAll, {
        checkAll: {
          ...state.query,
          type: cmpType
        }
      })
      await batchDel({
        agentIds: isSelectAll ? null : agentIds,
        groupNumber,
        ...(isSelectAll
          ? {
              checkAll: {
                ...state.query,
                type: cmpType.value
              }
            }
          : {})
      }).then(() => {
        ElMessage.success('操作成功')
      })
      onPageChange()
      sideRef.value.getData()
    }
    const onOpenDel = async (row: any, data?: any) => {
      await ElMessageBox.confirm('确认从服务组移除选中员工吗？', '移除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      })
      onDel(row, data)
    }
    const router = useRouter()
    const onJump = async (row: any) => {
      if (!row._id) {
        return router.push('/staff/department/staff_option')
      }
      const { _id } = row
      localforage.setItem(`${MEMBER_STORE_PRE}${_id}`, toRaw(row))
      router.push(`/staff/department/staff_option?id=${_id}`)
    }

    const ivrSaveSuccess = (): void => {
      state.showPage = false
      onPageChange()
    }

    const pageBack = (): void => {
      ElMessageBox.confirm('您没有进行保存操作, 确定离开页面吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        state.showPage = false
      })
    }
    onMounted(async () => {
      await mcGetCache.$getCache('userCache', 'hasObj')
    })
    const isGroup = computed(() => !URL_MAP.get((state.node as any)._id))
    const cmpType = computed(() => ((state.node as any)._id === UN_GROUP ? UN_GROUP : IS_GROUP))
    const cmpBatches = computed(() =>
      isGroup.value ? state.batchs : state.batchs.filter((_: any, m: number) => m !== state.batchs.length - 1)
    )
    const onNodeClick = async (node: any) => {
      tableRef.value.cancelSelectFun()
      state.node = node
      const isGroup = !URL_MAP.get(node._id)
      state.url = URL_MAP.get(node._id) || URL_MAP.get(IS_GROUP) || ''
      state.query.groups = isGroup ? [node.groupNumber] : []
      onPageChange()
    }

    return {
      pageBack,
      ivrSaveSuccess,
      onJump,
      onOpenDel,
      onChangeStatus,
      list,
      page,
      onPageChange,
      onPageSizeChange,
      Search,
      batchEdit,
      batchEditGroup,
      onBatchClick,
      onVisible,
      onHide,
      groupRules,
      onNodeClick,
      onConfirmGroup,
      cmpBatches,
      isGroup,
      tableRef,
      sideRef,
      groupRef,
      hasAgent,
      ...toRefs(state)
    }
  }
})
</script>
<style lang="stylus" scoped>
.flex
  display flex
  .wrapper
   width: calc(100vw - 400px);

.ml6
  margin-right: 6px;
.title
  font-weight: 500;
  font-size: 20px;
  color: rgba(0, 0, 0, 0.88);
.left-space
  margin-left 20px
.ml10
  margin-left 10px
  margin-right 10px
.dialog
  :deep(.el-form)
    padding-left: 24px;
  :deep(.el-dialog)
    width: 480px;
    height: 205px;
    border-radius: 4px;
  :deep(.el-dialog__body)
    display: flex;
    flex-direction: column
    padding: 10px 0 0 0;
    overflow unset
  :deep(.el-dialog__header)
    padding: 10px !important;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    margin-right: 0;
  :deep(.el-dialog__title)
    font-size: 16px;
    font-weight: 500;
    padding: 0 12px;
  :deep(.el-dialog__headerbtn)
    top: 0 !important;
    right: 12px;
  :deep(.el-select-v2__input-wrapper input)
    width 380px

  .btn-box
    height: 50px;
    margin-top: 10px;
    line-height: 50px;
    border-top: 1px solid rgba(0,0,0,0.05);
    padding-right: 24px;
    text-align: right;
    :deep(.el-button):nth-of-type(1)
      border: none;
</style>
